<?php 
namespace App\Console\Commands;

include base_path() . '/vendor/autoload.php';
use EasyWeChat\Foundation\Application;
use EasyWeChat\Message\Text;
use EasyWeChat\Message\Link;
use EasyWeChat\Message\News;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Redis;
use Log;
use DB;
use App\Club;
use App\User;

class ClearExpire extends Command {

    protected $config = [
        'app_id' => 'wx555be570d21859aa',
        'secret' => 'f92678be7687d1e1b1471ca9c066f242',
        'token' => 'leyougame2018'
    ];

    /**
     * The console command name.
     *
     * @var string
     */
    protected $name = 'clear:expire';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '';

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
    	$members = Club::where('type', '!=', 1)->get();//会员亲友圈
    	if ($members) {
    		foreach ($members as $member) {
    			$expire = substr($member->expiry_date, 0, 10);//到期时间
    			$current = time();
    			if ($expire > $current && ($expire - $current) <= 259200) {//会员还未到期，并还剩3天以内
    				$key = 'member_expire_alert_'.date('Y-m-d', time());
    				if (Redis::exists($key)) {//是否已记录本日通知
    					if (!Redis::sismember($key, $member->club_id)) {//未通知
	    					if ($this->sendMessage($member->creator, $expire)) {//发送成功
	    						Redis::sadd($key, $member->club_id);//记录通知
	    					}
    					}
    				} else {
    					if ($this->sendMessage($member->creator, $expire)) {//发送成功
    						Redis::sadd($key, $member->club_id);//记录通知
    					}
    				}
    			}
    		}
    	}
    }

    /**
     * [sendMessage 发送微信模板通知]
     * @param  [type] $userid [description]
     * @return [type]         [description]
     */
    private function sendMessage($userid, $expire)
    {	
    	$user = User::where(['userid' => $userid])->first();
    	if ($user) {
    		$agent = $user->agent();
    		if ($agent) {
	            $app = new Application($this->config);
	            $notice = $app->notice;
	            $userService = $app->user;
	            $member = $userService->get($agent->open_id);
	            $subscribe = $member->subscribe;
	            $url = "http://user.leyougame.cc/mobile/agent/friend_circle/control/".$agent->id;
	            if ($subscribe) {
	                $userId = $agent->open_id;
	                $templateId = 'wj6xb63Z9A6BR5uiDNUwqS8-9coA_e1XS2o89HRxoVo';
	                $data = array(
	                    "first" => "亲爱的乐游代理，您的会员亲友圈使用时间已经不足3天了!",
	                    "reason" => "会员将在".date('Y-m-d H:i:s', $expire)."到期",
	                    "state" => "会员亲友圈关闭",
	                    "remark" => "请尽快续费保证您的会员亲友圈正常使用!",
	                );
	                $result = $notice->uses($templateId)->withUrl($url)->andData($data)->andReceiver($userId)->send();
	                return true;
	            }
    		}
    	}

 		return false;
    }
}    